"""
Helper functions for creating user-friendly representations of serializer classes and serializer fields.

创建序列化器类和序列化器字段用户友好表示的辅助函数
"""

import re


def smart_repr(value: str) -> str:
    """ 智能表现 """

    value: str = repr(value)

    # 像 u"help text" 这样的表示应该简单地呈现为 "help text"
    if (
        value.startswith("u'")
        and value.endswith("'")
    ):
        return value[1:]

    # Representations like <django.core.validators.RegexValidator object at 0x1047af050>
    # Should be presented as <django.core.validators.RegexValidator object>
    return re.sub(" at 0x[0-9A-Fa-f]{4,32}>", ">", value)


def field_repr(
    field,
    force_many=False,
) -> str:
    """ 字段表现 """

    kwargs = field._kwargs  # noqa

    if force_many:
        kwargs = kwargs.copy()
        kwargs["many"] = True
        kwargs.pop("child", None)

    arg_string = ", ".join(
        smart_repr(val)
        for val in field._args  # noqa
    )
    kwarg_string = ", ".join(
        f"{key}={smart_repr(val)}"
        for key, val in sorted(kwargs.items())
    )

    if (
        arg_string
        and kwarg_string
    ):
        arg_string += ", "

    if force_many:
        class_name = force_many.__class__.__name__

    else:
        class_name = field.__class__.__name__

    return f"{class_name}({arg_string}{kwarg_string})"


def serializer_repr(serializer, indent: int, force_many=None):
    """ 序列化器表现 """

    ret = field_repr(serializer, force_many) + ":"
    indent_str = "    " * indent

    if force_many:
        fields = force_many.fields

    else:
        fields = serializer.fields

    for field_name, field in fields.items():
        ret += "\n" + indent_str + field_name + " = "

        if hasattr(field, "fields"):
            ret += serializer_repr(field, indent + 1)

        elif hasattr(field, "child"):
            ret += list_repr(field, indent + 1)

        elif hasattr(field, "child_relation"):
            ret += field_repr(field.child_relation, force_many=field.child_relation)

        else:
            ret += field_repr(field)

    if serializer.validators:
        ret += "\n" + indent_str + "class Meta:"
        ret += "\n" + indent_str + "    validators = " + smart_repr(serializer.validators)

    return ret


def list_repr(serializer, indent):
    """ 列表表现 """

    child = serializer.child

    if hasattr(child, "fields"):
        return serializer_repr(serializer, indent, force_many=child)

    return field_repr(serializer)
